//
//  mkMapTest0ViewController.m
//  mkMapTest0
//
//  Created by 鱼 bin on 12-6-3.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "mkMapTest0ViewController.h"



@implementation AnotationUnit

@synthesize title,subtitle,coordinate;


@end



@implementation mkMapTest0ViewController



/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	CGRect mapFrame = CGRectMake(0,0,320,460);
	testMapView = [[MKMapView alloc] initWithFrame:mapFrame];
	testMapView.delegate = self;
	testMapView.mapType = MKMapTypeHybrid;
	[self.view addSubview:testMapView];
	
	
	
	CLLocationManager *locationManager = [[CLLocationManager alloc] init];//创建位置管理器
	locationManager.delegate=self;//设置代理
	locationManager.desiredAccuracy=kCLLocationAccuracyBest;//指定需要的精度级别
	locationManager.distanceFilter=kCLDistanceFilterNone;//设置距离筛选器
	[locationManager startUpdatingLocation];//启动位置管理器
	MKCoordinateSpan theSpan;
	//地图的范围 越小越精确
	theSpan.latitudeDelta=0.05;
	theSpan.longitudeDelta=0.05;
	MKCoordinateRegion theRegion;
	theRegion.center=[[locationManager location] coordinate];
	NSLog(@"lo:%f la:%f",theRegion.center.longitude,theRegion.center.latitude);
	theRegion.span=theSpan;
	//[testMapView setRegion:theRegion];
	//testMapView.showsUserLocation = YES;
	[locationManager autorelease];
	
	
	 AnotationUnit* ann = [[AnotationUnit alloc] init];
	 ann.title = @"haha";
	 ann.subtitle = @"sub haha";
	 CLLocationCoordinate2D coor = theRegion.center;
	 ann.coordinate = coor;
	 [testMapView addAnnotation:ann];
	
	double startTime = [[NSDate date] timeIntervalSince1970];
	//[self createPlateLineBin];
	[self addPlateLineFromBin];
	double useTime = [[NSDate date] timeIntervalSince1970] - startTime;
	NSLog(@"useTime:%f",useTime);

}

-(void)addPlateLineFromBin{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString* platesBinPath = [documentsDirectory stringByAppendingPathComponent:@"earthPlates.bin"];
	platesBinPath = [[NSBundle mainBundle] pathForResource:@"earthPlates" ofType:@"bin"];
	FILE* platesFile = fopen([platesBinPath cStringUsingEncoding:NSUTF8StringEncoding], "r");

	fseek(platesFile, 0, SEEK_SET);
	fseek(platesFile, 0, SEEK_END);
	int dataLen = ftell(platesFile);
	fseek(platesFile, 0, SEEK_SET);
	NSLog(@"dataLen:%d",dataLen);
	unsigned char* platesData = (unsigned char*)malloc(dataLen);
	fread(platesData,dataLen,1,platesFile);
	fclose(platesFile);
		
	int dataIndex = 0; //数据索引指向
	
	//区块
	int* platesCountPtr = (int*)(platesData + dataIndex);  //区块数
	dataIndex += 4;
	NSLog(@"*platesCountPtr:%d",*platesCountPtr);
	for (int platesIndex = 0; platesIndex < *platesCountPtr; platesIndex++) {
		unsigned int* platesColorPtr = (unsigned int*)(platesData + dataIndex); //颜色
		dataIndex += 4;
		int* lineCountPtr = (int*)(platesData + dataIndex);  //线条数目
		dataIndex += 4;
		//线条
		NSLog(@"*lineCountPtr:%d",*lineCountPtr);
		for (int lineIndex = 0; lineIndex < *lineCountPtr; lineIndex++) {
			int* pointCountPtr = (int*)(platesData + dataIndex);
			dataIndex += 4;
			//一根线
			CLLocationCoordinate2D* coord = (CLLocationCoordinate2D*)(platesData + dataIndex);
			dataIndex += (*pointCountPtr)*sizeof(CLLocationCoordinate2D);
			EWmapLine* line = [EWmapLine maplineWithCoordinates:coord count:(*pointCountPtr)];
			[line setColor:[UIColor uintToColor:(*platesColorPtr)]];
			[testMapView addOverlay:line];
		}
	}
	free(platesData);
}


-(void)createPlateLineBin{
	//NSString* testStr = @"helloworld";
	//NSRange range = {5,1};
	//range.location = 5;
	//range.length = 1;
	//NSLog(@"sub :%@",[testStr substringWithRange:range]);
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString* platesBinPath = [documentsDirectory stringByAppendingPathComponent:@"earthPlates.bin"];
	FILE* platesFile = fopen([platesBinPath cStringUsingEncoding:NSUTF8StringEncoding], "w+");

	
	
	NSString* path = [[NSBundle mainBundle] pathForResource:@"Earths_Tectonic_Plates" ofType:@"kml"];
	
	//NSString* path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"xml"];
	
	
	EWxmlNode* rootNode = [EWxmlNode xmlRootWithPath:path];
	//NSLog(@"rootNode:%@",[rootNode getNodeContentString]);
	
	NSMutableArray* placeMarkNodes = [rootNode getSubNodes:@"Placemark"];
	
	NSLog(@"palceMarkNodecount:%d",placeMarkNodes.count);
	int placecount = placeMarkNodes.count;      // placecount = 1;
	fwrite(&placecount, 4, 1, platesFile);   //区块数
	for (int placeIndex = 0; placeIndex < placecount;placeIndex++) {
		
		EWxmlNode* geometryNode = [placeMarkNodes objectAtIndex:placeIndex];
		//提取颜色值
		NSArray* colorNodes = [geometryNode getSubNodes:@"styleUrl"];
		EWxmlNode* colorNode = [colorNodes objectAtIndex:0];
		NSString* colorStr = [colorNode getNodeContentString];
		NSLog(@"color:%@",colorStr);
		UIColor* lineColor = [EWmapLine getUIColorWithStr:colorStr];
		unsigned int intColor = [lineColor colorToUint];
		fseek(platesFile, 0, SEEK_END);
		fwrite(&intColor, 4, 1, platesFile);   //颜色值
		
		NSMutableData* linePointData = [NSMutableData dataWithCapacity:1000];
		
		//NSLog(@"subNode description:%@",[subNode getNodeContentString]);
		NSArray* lineArray = [geometryNode getSubNodes:@"LineString"];
		int LineCount = lineArray.count; // NSLog(@"LineCount:%d",LineCount) ;LineCount = 1;
		int realLineCount = 0;
		for (int lineIndex = 0;lineIndex < LineCount;lineIndex++) {
			EWxmlNode* LineStringNode = [lineArray objectAtIndex:lineIndex];
			
			NSArray* coordStr = [LineStringNode splitContentWith:@","];
			if (coordStr.count%2 != 0) {
				NSLog(@"debug奇数");
			}

			int pointCount = coordStr.count/2; 
			//还要考虑是否穿过了180经线
			int pointStart = 0;
			int pointEnd = pointCount - 1;
			CLLocationCoordinate2D* lineCoor = (CLLocationCoordinate2D*)malloc(pointCount*sizeof(CLLocationCoordinate2D));
			for (int i = 0; i < pointCount - 1; i++) {
				int coordStrIndex = 2*i;
				int nextcoordStrIndex = 2*(i + 1);
				float longitude = [[coordStr objectAtIndex:coordStrIndex] floatValue];
				float latitude = [[coordStr objectAtIndex:coordStrIndex + 1] floatValue];
				
				float nextlongitude = [[coordStr objectAtIndex:nextcoordStrIndex] floatValue];
				float nextlatitude = [[coordStr objectAtIndex:nextcoordStrIndex + 1] floatValue];
				if (longitude*nextlongitude < 0) {
					//有穿过180度经线情况，线段中止并绘制，以下一个点为起始点绘制下一条线。
					pointEnd = i;
					//EWmapLine* line = [EWmapLine maplineWithCoordinates:lineCoor + pointStart count:pointEnd - pointStart + 1];
					//[testMapView addOverlay:line];
					int pointNum = pointEnd - pointStart + 1;
					[linePointData appendBytes:&pointNum length:4];
					[linePointData appendBytes:lineCoor + pointStart length:pointNum*sizeof(CLLocationCoordinate2D)];
					pointStart = i + 1;
					realLineCount++;
				}
				lineCoor[i].longitude = longitude;
				lineCoor[i].latitude = latitude;
				lineCoor[i + 1].longitude = nextlongitude;
				lineCoor[i + 1].latitude = nextlatitude;
			}
			CLLocationCoordinate2D* startCoord = lineCoor + pointStart;
			//EWmapLine* line = [EWmapLine maplineWithCoordinates:startCoord count:pointEnd - pointStart + 1];
			//[testMapView addOverlay:line];
			int pointNum = pointEnd - pointStart + 1;
			[linePointData appendBytes:&pointNum length:4];
			[linePointData appendBytes:startCoord length:pointNum*sizeof(CLLocationCoordinate2D)];
			realLineCount++;
			
			free(lineCoor);
		}
		//完成一个颜色区块的数据,并写入
		fseek(platesFile, 0, SEEK_END);
		fwrite(&realLineCount, 4, 1, platesFile);
		fseek(platesFile, 0, SEEK_END);
		fwrite([linePointData bytes], [linePointData length],1, platesFile);
		fflush(platesFile);	
	}
	
	fclose(platesFile);
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
	NSLog(@"did");
	
}


- (void)mapView:(MKMapView *)amapView didSelectAnnotationView:(MKAnnotationView *)view
{
	//AnotationUnit *annotation = view.annotation;
	float lat = view.annotation.coordinate.latitude;
	float lng = view.annotation.coordinate.longitude;
	NSLog(@"点击位置：(%f,%f)",lat,lng);
}

-(MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
	NSLog(@"viewForAnnotation :%@",annotation.title);
	
	
	 MKPinAnnotationView *pinView = nil;
	 static NSString *defaultPinID = @"com.invasivecode.pin";
	 pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
	 if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
	 initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
	 pinView.pinColor = MKPinAnnotationColorGreen;
	 pinView.canShowCallout = YES;
	 pinView.animatesDrop = YES;
	 //[mapView.userLocation setTitle:@"欧陆经典"];
	 //[mapView.userLocation setSubtitle:@"vsp"];
	 return pinView;
	 
	//return [kmlParser viewForAnnotation:annotation];
	
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
	MKPolylineView* overView = nil;
	
	//[overView retain];
	if ([overlay isKindOfClass:[EWmapLine class]]) {
		EWmapLine* mapLine = (EWmapLine*)overlay;
		MKPolyline* polyline = [mapLine polyline];
		overView = [[MKPolylineView alloc] initWithPolyline:polyline];
		overView.strokeColor = [mapLine color];
		overView.lineWidth = 3;
	}
	
	if ([overlay isKindOfClass:[MKPolyline class]]) {
		overView = [[MKPolylineView alloc] initWithPolyline:overlay];
		overView.strokeColor = [UIColor greenColor];
		
		overView.lineWidth = 3;
	}

	

	[overView autorelease];
	 
	return overView;

}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
